package com.gitee.cui.netty.protocol;

import com.gitee.cui.netty.NettyDemoConfig;
import com.gitee.cui.netty.echoServer.NettyEchoClientHandler;
import com.gitee.cui.util.Logger;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.nio.charset.StandardCharsets;

/**
 * Netty循环发送字符串客户端，用于演示“全包”、“粘包”、“半包”问题
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/10/25 12:00
 **/
public class NettyDumpSendClient {

    private int serverPort;

    private String serverIp;

    private Bootstrap bootstrap = new Bootstrap();

    public NettyDumpSendClient(String serverIp, int serverPort) {
        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }

    public static void main(String[] args) {
        new NettyDumpSendClient(NettyDemoConfig.SOCKET_SERVER_IP, NettyDemoConfig.SOCKET_SERVER_PORT).runClient();
    }

    /**
     * 运行客户端程序
     */
    private void runClient() {
        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {
            bootstrap.group(worker);
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(NettyEchoClientHandler.INSTANCE);
                }
            });
            bootstrap.remoteAddress(serverIp, serverPort);
            ChannelFuture future = bootstrap.connect();
            // 添加监听
            future.addListener(listener -> {
                if (listener.isSuccess()) {
                    Logger.info("EchoDumpSendClient客户端连接成功！");
                } else {
                    Logger.info("EchoDumpSendClient客户端连接失败！");
                }
            });
            future.sync();

            // 发送请求
            String content = "测试字符串内容";
            byte[] bytes = content.getBytes(StandardCharsets.UTF_8);
            Channel channel = future.channel();
            for (int i = 0; i < 1000; i++) {
                ByteBuf buffer = channel.alloc().buffer();
                buffer.writeBytes(bytes);
                channel.writeAndFlush(buffer);
            }

            ChannelFuture closeFuture = channel.closeFuture();
            closeFuture.sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            worker.shutdownGracefully();
        }

    }
}
